package servicios.biziGasteizAdmin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONObject;

import connection.BDConnection;

/**
 * Servlet implementation class ConcertsServices
 */
public class SportsServices extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String CONTENT_TYPE = "text/json";
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SportsServices() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if(!isMultipart)
				processRequest(request, response);
			else
				proccessMultiparRequest(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if(!isMultipart)
				processRequest(request, response);
			else
				proccessMultiparRequest(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		}
	}
	
	private void proccessMultiparRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{
		response.setContentType("text/html");
		String requestP = request.getParameter("request");
		if(requestP.compareToIgnoreCase("NEWSPORT") == 0){
			newSports(request, response);
		}   
		else if(requestP.compareToIgnoreCase("UPDATESPORT") == 0){
			updateSports(request, response);
		}
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		response.setContentType(CONTENT_TYPE);
		String requestP = request.getParameter("request");
		if(requestP.compareToIgnoreCase("GETSPORTS") == 0){
			getSports(request, response);
		}
		if(requestP.compareToIgnoreCase("DELETEROW") == 0){
			deleteRow(request, response);
		}
		else if(requestP.compareToIgnoreCase("GETCODLUGARES") == 0){
			getCodVentas(request, response);
		}
	}
	
	private void getCodVentas(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			String sqlStr = "SELECT * FROM LUGARES";
			ResultSet rs = bdCon.executeQuery(sqlStr);
			JSONObject resJson = new JSONObject();
			resJson.put("success", true);
			JSONArray itemsArray = new JSONArray(); 
			while(rs.next()){
				JSONObject item = new JSONObject();
				item.put("nombre", rs.getString("nombre"));
				item.put("codigo", rs.getString("codigo"));
				itemsArray.put(item);
			}
			resJson.put("data", itemsArray);
			
			response.getWriter().write(resJson.toString());
			
			bdCon.closeConnection(rs);
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	
	
private void updateSports(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
			String sqlQuery = "UPDATE DEPORTES SET ";
			String codigo = "";
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();

	                if(fieldname.equals("precio_taquilla")){
	                	sqlQuery += fieldname+"="+fieldvalue+",";
	                }
	                else if(fieldname.equals("precio_anticipado")){
	                	sqlQuery += fieldname+"="+fieldvalue+",";
	                }
	                else if(fieldname.equals("destacado")){
	                	sqlQuery += fieldname+"="+fieldvalue+",";
	                }
	                else if(fieldname.equals("mini_destacado")){
	                	sqlQuery += fieldname+"="+fieldvalue+",";
	                }
	                else if(fieldname.equals("fecha")){
	                	String[] fecha = fieldvalue.split("/");
	                	String laFecha = fecha[2]+"-"+fecha[0]+"-"+fecha[1];
	                	sqlQuery += fieldname+"='"+laFecha+"',";
	                }
	                else if(fieldname.equals("codigo")){
	                	codigo = fieldvalue;
	                }
	                else{
	                	sqlQuery += fieldname+"='"+fieldvalue+"',";
	                }
	            } else {
	            	
	                String fieldname = item.getFieldName();
	                String filename = item.getName();
	                InputStream filecontent = item.getInputStream();
	                
	                sqlQuery += fieldname+"='/images/eventos/deportes/"+filename+"',";
	                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/deportes");
	                File f=new File(relativePath+File.separator+filename);//Aqui le dan el nombre y/o con la ruta del archivo salida
	                OutputStream os=new FileOutputStream(f);
	                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
	                int len;
	                while((len=filecontent.read(buf))>0){
	                	os.write(buf,0,len);
	                }
	                os.close();
	                filecontent.close();
	            }
	        }
	        sqlQuery = sqlQuery.substring(0,sqlQuery.length()-1);
        	sqlQuery += " WHERE cod="+codigo;
        	System.out.println(sqlQuery);
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
	        
		}catch(Exception o){
			o.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+o.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	
	
	private void newSports(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{
		
		String values = "";
		String columns= "";
		String sqlQuery = "";
		BDConnection bdCon = new BDConnection();
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();

	                if(fieldname.equals("precio_taquilla")){
	                	values = values + fieldvalue +",";
	                	columns = columns + fieldname +",";
	                }
	                else if(fieldname.equals("precio_anticipado")){
	                	values = values + fieldvalue +",";
	                	columns = columns + fieldname +",";
	                }
	                else if(fieldname.equals("destacado")){
	                	values = values + fieldvalue +",";
	                	columns = columns + fieldname +",";
	                }
	                else if(fieldname.equals("mini_destacado")){
	                	values = values + fieldvalue +",";
	                	columns = columns + fieldname +",";
	                }
	                else if(fieldname.equals("fecha")){
	                	String[] fecha = fieldvalue.split("/");
	                	String laFecha = fecha[2]+"-"+fecha[0]+"-"+fecha[1];
	                	values = values + "'"+laFecha+"',";
	                	columns = columns + fieldname+",";
	                }
	                else{
	                	values = values + "'"+fieldvalue +"',";
	                	columns = columns + fieldname +",";
	                }
	            } else {
	            	
	                String fieldname = item.getFieldName();
	                String filename = item.getName();
	                InputStream filecontent = item.getInputStream();
	                values = values + "'/images/eventos/deportes/"+filename+"',";
	                columns = columns + fieldname+",";
	                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/deportes");
	                File f=new File(relativePath+File.separator+filename);//Aqui le dan el nombre y/o con la ruta del archivo salida
	                OutputStream os=new FileOutputStream(f);
	                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
	                int len;
	                while((len=filecontent.read(buf))>0){
	                	os.write(buf,0,len);
	                }
	                os.close();
	                filecontent.close();
	            }
	        }
        	values = values.substring(0,values.length() -1);
        	columns = columns.substring(0, columns.length() -1);
        	sqlQuery = "INSERT INTO DEPORTES ("+columns+") VALUES ("+values+")";
        	System.out.println(sqlQuery);
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
	        
		}catch(Exception o){
			o.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+o.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void deleteRow(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			String codigo = request.getParameter("codigo");
			String sqlStr = "DELETE FROM DEPORTES WHERE COD = "+codigo+"";
			
			JSONObject resJson = new JSONObject();
			int rs = bdCon.executeUpdate(sqlStr);
			if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void getSports(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			String sqlStr = "SELECT * FROM DEPORTES";
			ResultSet rs = bdCon.executeQuery(sqlStr);
			JSONObject resJson = new JSONObject();
			resJson.put("success", true);
			JSONArray itemsArray = new JSONArray(); 
			while(rs.next()){
				JSONObject item = new JSONObject();
				item.put("nombre", rs.getString("nombre"));
				item.put("descripcion_corta", rs.getString("descripcion_corta"));
				item.put("descripcion_larga", rs.getString("descripcion_larga"));
				item.put("descripcion_normal", rs.getString("descripcion_normal"));
				item.put("fecha", rs.getDate("fecha"));
				item.put("hora", rs.getTime("hora"));
				item.put("cod_lugar", rs.getString("cod_lugar"));
				item.put("precio_anticipado", rs.getDouble("precio_anticipado"));
				item.put("precio_taquilla", rs.getDouble("precio_taquilla"));
				item.put("foto_pequena", rs.getString("foto_pequena"));
				item.put("foto_grande", rs.getString("foto_grande"));
				item.put("cartel", rs.getString("cartel"));
				item.put("destacado", rs.getBoolean("destacado"));
				item.put("mini_destacado", rs.getBoolean("mini_destacado"));
				item.put("video", rs.getString("video"));
				item.put("enlaces", rs.getString("enlaces"));
				item.put("cod", rs.getString("cod"));
				itemsArray.put(item);
			}
			resJson.put("data", itemsArray);
			
			response.getWriter().write(resJson.toString());
			
			bdCon.closeConnection(rs);
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
}
